package cn.wolfcode.cloud.shop.web.controller;


import cn.wolfcode.cloud.shop.redis.SeckillRedisKey;
import cn.wolfcode.cloud.shop.resp.Result;
import cn.wolfcode.cloud.shop.service.ISeckillGoodService;
import cn.wolfcode.cloud.shop.util.JSONUtil;
import cn.wolfcode.cloud.shop.vo.SeckillGoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("/seckillGoods")
public class SeckillGoodsController {

    @Autowired
    private ISeckillGoodService seckillGoodService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 优化前:
     *   qps:2700/sec
     * 优化后:
     *   qps:4700/sec
     * @return
     */
    @GetMapping("/query")
    public Result<?> query(){
        List<SeckillGoodsVo> seckillGoodsVos = seckillGoodService.queryByCache();
        System.out.println(seckillGoodsVos.size());
        return Result.success(seckillGoodsVos);
    }

    @RequestMapping("/{id}")
    public Result<?> queryById(@PathVariable("id") Long id){

        return Result.success(seckillGoodService.queryByIdInCache(id));
    }


    @GetMapping("/initData")
    public Result<?> initData(){
        List<SeckillGoodsVo> seckillGoodsVos = seckillGoodService.query();
        for (SeckillGoodsVo seckillGoodsVo : seckillGoodsVos) {
            redisTemplate.opsForHash().put(SeckillRedisKey.SECKILL_GOODS_HASH.getRealKey(""),
                seckillGoodsVo.getId()+"",
                JSONUtil.toJsonString(seckillGoodsVo));

            redisTemplate.opsForHash().put(SeckillRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(""),
                seckillGoodsVo.getId()+"",
                seckillGoodsVo.getStockCount()+"");
        }

        return Result.success();
    }
}
